// 数据预处理管道系统 - 前端应用逻辑

// 全局变量
let currentStep = 1;
let availableMethods = [];
let currentConfig = null;
let socket = null;
let sessionId = null;

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
    setupEventListeners();
    loadAvailableMethods();
});

// 初始化应用
function initializeApp() {
    // 初始化Socket.IO连接
    socket = io();
    
    // 设置Socket事件监听
    setupSocketListeners();
    
    // 检查应用状态
    checkAppStatus();
    
    console.log('应用初始化完成');
}

// 设置事件监听器
function setupEventListeners() {
    // 文件上传
    const fileInput = document.getElementById('file-input');
    const uploadArea = document.getElementById('upload-area');
    
    fileInput.addEventListener('change', handleFileSelect);
    
    // 拖拽上传
    uploadArea.addEventListener('dragover', handleDragOver);
    uploadArea.addEventListener('dragleave', handleDragLeave);
    uploadArea.addEventListener('drop', handleFileDrop);
    uploadArea.addEventListener('click', () => fileInput.click());
    
    // 层数选择
    const layerCount = document.getElementById('layer-count');
    layerCount.addEventListener('change', updateLayerConfig);
}

// 设置Socket监听器
function setupSocketListeners() {
    socket.on('connect', function() {
        console.log('WebSocket连接成功');
    });
    
    socket.on('processing_started', function(data) {
        console.log('处理开始:', data);
        showProcessingProgress(data.total_combinations);
    });
    
    socket.on('processing_progress', function(data) {
        console.log('处理进度:', data);
        updateProcessingProgress(data);
    });
    
    socket.on('processing_completed', function(data) {
        console.log('处理完成:', data);
        showProcessingResults(data);
    });
    
    socket.on('processing_error', function(data) {
        console.log('处理错误:', data);
        showError('处理失败: ' + data.error);
        hideLoading();
    });
}

// 检查应用状态
async function checkAppStatus() {
    try {
        const response = await fetch('/api/status');
        const data = await response.json();
        
        if (data.success) {
            const status = data.status;
            sessionId = status.session_id;
            
            if (status.has_data) {
                // 如果已有数据，跳到相应步骤
                if (status.has_config) {
                    if (status.processing_status === 'completed') {
                        goToStep(4);
                        loadResults();
                    } else if (status.processing_status === 'processing') {
                        goToStep(3);
                        showProcessingInProgress();
                    } else {
                        goToStep(3);
                    }
                } else {
                    goToStep(2);
                }
            }
        }
    } catch (error) {
        console.error('检查状态失败:', error);
    }
}

// 加载可用方法
async function loadAvailableMethods() {
    try {
        const response = await fetch('/api/methods');
        const data = await response.json();
        
        if (data.success) {
            availableMethods = data.methods;
            displayAvailableMethods();
            updateLayerConfig(); // 初始化层配置
        } else {
            showError('加载预处理方法失败: ' + data.error);
        }
    } catch (error) {
        console.error('加载方法失败:', error);
        showError('加载预处理方法失败');
    }
}

// 显示可用方法
function displayAvailableMethods() {
    const container = document.getElementById('available-methods');
    container.innerHTML = '';
    
    availableMethods.forEach(method => {
        const methodCard = document.createElement('div');
        methodCard.className = 'col-md-6 col-lg-4 mb-2';
        methodCard.innerHTML = `
            <div class="method-card" data-method-id="${method.id}">
                <div class="d-flex align-items-center">
                    <span class="badge bg-primary me-2">${method.id}</span>
                    <div>
                        <div class="fw-bold">${method.name}</div>
                        <small class="text-muted">${method.description}</small>
                    </div>
                </div>
            </div>
        `;
        container.appendChild(methodCard);
    });
}

// 处理文件选择
function handleFileSelect(event) {
    const file = event.target.files[0];
    if (file) {
        uploadFile(file);
    }
}

// 处理拖拽
function handleDragOver(event) {
    event.preventDefault();
    event.currentTarget.classList.add('dragover');
}

function handleDragLeave(event) {
    event.currentTarget.classList.remove('dragover');
}

function handleFileDrop(event) {
    event.preventDefault();
    event.currentTarget.classList.remove('dragover');
    
    const files = event.dataTransfer.files;
    if (files.length > 0) {
        uploadFile(files[0]);
    }
}

// 上传文件
async function uploadFile(file) {
    // 验证文件类型
    const allowedTypes = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 
                         'application/vnd.ms-excel'];
    if (!allowedTypes.includes(file.type) && !file.name.match(/\.(xlsx|xls)$/i)) {
        showError('请选择Excel文件 (.xlsx 或 .xls)');
        return;
    }
    
    // 验证文件大小 (100MB)
    if (file.size > 100 * 1024 * 1024) {
        showError('文件大小不能超过100MB');
        return;
    }
    
    showLoading();
    
    const formData = new FormData();
    formData.append('file', file);
    
    try {
        const response = await fetch('/api/upload', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            sessionId = data.session_id;
            showFileInfo(data);
            showDataPreview(data.data_info.preview);
            showSuccess('文件上传成功');
            
            // 自动跳转到下一步
            setTimeout(() => goToStep(2), 1500);
        } else {
            showError(data.error);
        }
    } catch (error) {
        console.error('上传失败:', error);
        showError('文件上传失败');
    } finally {
        hideLoading();
    }
}

// 显示文件信息
function showFileInfo(data) {
    const fileInfo = document.getElementById('file-info');
    const fileDetails = document.getElementById('file-details');
    
    fileDetails.innerHTML = `
        <div class="row">
            <div class="col-md-6">
                <strong>文件名:</strong> ${data.filename}
            </div>
            <div class="col-md-6">
                <strong>数据维度:</strong> ${data.data_info.rows} 行 × ${data.data_info.columns} 列
            </div>
        </div>
    `;
    
    fileInfo.style.display = 'block';
}

// 显示数据预览
function showDataPreview(preview) {
    if (!preview || preview.error) {
        return;
    }
    
    const previewDiv = document.getElementById('data-preview');
    const table = document.getElementById('preview-table');
    
    // 生成表头
    let html = '<thead><tr>';
    preview.columns.forEach(col => {
        html += `<th>${col}</th>`;
    });
    html += '</tr></thead>';
    
    // 生成数据行
    html += '<tbody>';
    preview.rows.forEach(row => {
        html += '<tr>';
        row.forEach(cell => {
            html += `<td>${cell}</td>`;
        });
        html += '</tr>';
    });
    html += '</tbody>';
    
    table.innerHTML = html;
    previewDiv.style.display = 'block';
}

// 更新层配置
function updateLayerConfig() {
    const layerCount = parseInt(document.getElementById('layer-count').value);
    const container = document.getElementById('layer-config');
    
    container.innerHTML = '';
    
    for (let i = 1; i <= layerCount; i++) {
        const layerDiv = document.createElement('div');
        layerDiv.className = 'layer-config-item';
        layerDiv.innerHTML = `
            <div class="layer-title">
                <i class="fas fa-layer-group me-2"></i>第 ${i} 层预处理方法
            </div>
            <div class="row" id="layer-${i}-methods">
                ${generateMethodCheckboxes(i)}
            </div>
            <div class="mt-2">
                <small class="text-muted">
                    <i class="fas fa-info-circle me-1"></i>
                    可以选择多个方法，系统会生成所有可能的组合
                </small>
            </div>
        `;
        container.appendChild(layerDiv);
    }
    
    // 添加事件监听器
    setupMethodSelection();
    updateCombinationSummary();
}

// 生成方法复选框
function generateMethodCheckboxes(layerIndex) {
    let html = '';
    
    availableMethods.forEach(method => {
        html += `
            <div class="col-md-6 col-lg-4 mb-2">
                <div class="form-check">
                    <input class="form-check-input method-checkbox" 
                           type="checkbox" 
                           id="layer-${layerIndex}-method-${method.id}"
                           data-layer="${layerIndex}" 
                           data-method="${method.id}"
                           ${method.id === 0 ? 'checked' : ''}>
                    <label class="form-check-label" for="layer-${layerIndex}-method-${method.id}">
                        <span class="badge bg-primary me-2">${method.id}</span>
                        ${method.name}
                    </label>
                </div>
            </div>
        `;
    });
    
    return html;
}

// 设置方法选择事件
function setupMethodSelection() {
    const checkboxes = document.querySelectorAll('.method-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateCombinationSummary);
    });
}

// 更新组合摘要
function updateCombinationSummary() {
    const layerCount = parseInt(document.getElementById('layer-count').value);
    const layerSelections = [];
    let totalCombinations = 1;
    let hasSelection = true;
    
    for (let i = 1; i <= layerCount; i++) {
        const checkboxes = document.querySelectorAll(`input[data-layer="${i}"]:checked`);
        const selectedMethods = Array.from(checkboxes).map(cb => parseInt(cb.dataset.method));
        
        if (selectedMethods.length === 0) {
            hasSelection = false;
            break;
        }
        
        layerSelections.push(selectedMethods);
        totalCombinations *= selectedMethods.length;
    }
    
    const summaryDiv = document.getElementById('combination-summary');
    const detailsDiv = document.getElementById('combination-details');
    
    if (hasSelection) {
        let html = `
            <div class="row">
                <div class="col-md-6">
                    <strong>总组合数:</strong> ${totalCombinations}
                </div>
                <div class="col-md-6">
                    <strong>预计处理时间:</strong> ${estimateProcessingTime(totalCombinations)}
                </div>
            </div>
        `;
        
        if (totalCombinations > 1000) {
            html += `
                <div class="alert alert-warning mt-2 mb-0">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    组合数量较多，处理可能需要较长时间
                </div>
            `;
        }
        
        detailsDiv.innerHTML = html;
        summaryDiv.style.display = 'block';
    } else {
        summaryDiv.style.display = 'none';
    }
}

// 估算处理时间
function estimateProcessingTime(combinations) {
    const timePerCombination = 0.5; // 假设每个组合0.5秒
    const totalSeconds = combinations * timePerCombination;
    
    if (totalSeconds < 60) {
        return `约 ${Math.ceil(totalSeconds)} 秒`;
    } else if (totalSeconds < 3600) {
        return `约 ${Math.ceil(totalSeconds / 60)} 分钟`;
    } else {
        return `约 ${Math.ceil(totalSeconds / 3600)} 小时`;
    }
}

// 配置处理
async function configureProcessing() {
    const layerCount = parseInt(document.getElementById('layer-count').value);
    const layerSelections = [];
    
    // 收集每层的选择
    for (let i = 1; i <= layerCount; i++) {
        const checkboxes = document.querySelectorAll(`input[data-layer="${i}"]:checked`);
        const selectedMethods = Array.from(checkboxes).map(cb => parseInt(cb.dataset.method));
        
        if (selectedMethods.length === 0) {
            showError(`第 ${i} 层必须至少选择一个方法`);
            return;
        }
        
        layerSelections.push(selectedMethods);
    }
    
    showLoading();
    
    try {
        const response = await fetch('/api/configure', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                layer_count: layerCount,
                layer_selections: layerSelections
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            currentConfig = data.config;
            showSuccess('配置成功');
            showConfigConfirmation(data.config);
            goToStep(3);
        } else {
            showError(data.error);
        }
    } catch (error) {
        console.error('配置失败:', error);
        showError('配置失败');
    } finally {
        hideLoading();
    }
}

// 显示配置确认
function showConfigConfirmation(config) {
    const container = document.getElementById('config-confirmation');
    
    let html = `
        <div class="alert alert-info">
            <h6><i class="fas fa-info-circle me-2"></i>配置确认</h6>
            <div class="row">
                <div class="col-md-4">
                    <strong>处理层数:</strong> ${config.layer_count}
                </div>
                <div class="col-md-4">
                    <strong>总组合数:</strong> ${config.total_combinations}
                </div>
                <div class="col-md-4">
                    <strong>输出目录:</strong> ${config.output_directory}
                </div>
            </div>
        </div>
    `;
    
    container.innerHTML = html;
}

// 开始处理
async function startProcessing() {
    if (!currentConfig) {
        showError('请先配置处理参数');
        return;
    }
    
    showLoading();
    
    try {
        const response = await fetch('/api/process', {
            method: 'POST'
        });
        
        const data = await response.json();
        
        if (data.success) {
            showSuccess('处理已开始');
            document.getElementById('start-processing-btn').disabled = true;
        } else {
            showError(data.error);
        }
    } catch (error) {
        console.error('启动处理失败:', error);
        showError('启动处理失败');
    } finally {
        hideLoading();
    }
}

// 显示处理进度
function showProcessingProgress(totalCombinations) {
    const progressDiv = document.getElementById('processing-progress');
    progressDiv.style.display = 'block';
    
    updateStatusIndicator('processing', '处理中');
}

// 更新处理进度
function updateProcessingProgress(data) {
    const progressBar = document.getElementById('progress-bar');
    const progressDetails = document.getElementById('progress-details');
    
    const percentage = Math.round(data.percentage);
    
    progressBar.style.width = `${percentage}%`;
    progressBar.textContent = `${percentage}%`;
    
    progressDetails.innerHTML = `
        正在处理组合 ${data.current}/${data.total} - ${data.combination_id}
    `;
}

// 显示处理结果
function showProcessingResults(results) {
    hideLoading();
    updateStatusIndicator('completed', '处理完成');
    
    // 显示统计信息
    const statsContainer = document.getElementById('result-statistics');
    statsContainer.innerHTML = `
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-number">${results.total_combinations}</div>
                <div class="stat-label">总组合数</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card success">
                <div class="stat-number">${results.successful_combinations}</div>
                <div class="stat-label">成功处理</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card warning">
                <div class="stat-number">${results.failed_combinations}</div>
                <div class="stat-label">处理失败</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card info">
                <div class="stat-number">${Math.round(results.success_rate)}%</div>
                <div class="stat-label">成功率</div>
            </div>
        </div>
    `;
    
    // 显示文件列表
    displayFileList(results.files);
    
    goToStep(4);
}

// 显示文件列表
function displayFileList(files) {
    const container = document.getElementById('file-list');
    
    if (files.length === 0) {
        container.innerHTML = '<div class="alert alert-warning">没有生成文件</div>';
        return;
    }
    
    let html = '';
    files.forEach((file, index) => {
        html += `
            <div class="file-item">
                <div class="row align-items-center">
                    <div class="col-md-6">
                        <div class="fw-bold">${file.filename}</div>
                        <small class="text-muted">组合: ${file.combination_id}</small>
                    </div>
                    <div class="col-md-4">
                        <small class="text-muted">
                            方法: ${file.methods.join(' → ')}
                        </small>
                    </div>
                    <div class="col-md-2 text-end">
                        <button class="btn btn-sm btn-outline-primary" 
                                onclick="downloadFile('${file.filename}')">
                            <i class="fas fa-download me-1"></i>下载
                        </button>
                    </div>
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 下载文件
function downloadFile(filename) {
    window.open(`/api/download/${filename}`, '_blank');
}

// 打开输出目录
async function openOutputDirectory() {
    try {
        const response = await fetch('/api/open-directory');
        const data = await response.json();
        
        if (data.success) {
            showSuccess('已打开保存目录');
        } else {
            showError(data.error);
        }
    } catch (error) {
        console.error('打开目录失败:', error);
        showError('打开目录失败');
    }
}

// 开始新的处理
function startNew() {
    if (confirm('确定要开始新的处理吗？当前数据将被清除。')) {
        location.reload();
    }
}

// 步骤导航
function goToStep(step) {
    // 隐藏所有步骤内容
    document.querySelectorAll('.step-content').forEach(content => {
        content.style.display = 'none';
    });
    
    // 显示目标步骤
    document.getElementById(`content-step-${step}`).style.display = 'block';
    
    // 更新步骤指示器
    updateStepIndicator(step);
    
    currentStep = step;
}

// 更新步骤指示器
function updateStepIndicator(activeStep) {
    document.querySelectorAll('.step').forEach((step, index) => {
        const stepNumber = index + 1;
        step.classList.remove('active', 'completed');
        
        if (stepNumber === activeStep) {
            step.classList.add('active');
        } else if (stepNumber < activeStep) {
            step.classList.add('completed');
        }
    });
}

// 更新状态指示器
function updateStatusIndicator(status, text) {
    const indicator = document.getElementById('status-indicator');
    
    // 移除所有状态类
    indicator.className = 'navbar-text';
    
    // 添加新状态类
    indicator.classList.add(`status-${status}`);
    
    // 更新图标和文本
    let icon = 'fas fa-circle';
    switch (status) {
        case 'ready':
            icon = 'fas fa-circle text-secondary';
            break;
        case 'processing':
            icon = 'fas fa-spinner fa-spin text-warning';
            break;
        case 'completed':
            icon = 'fas fa-check-circle text-success';
            break;
        case 'error':
            icon = 'fas fa-exclamation-circle text-danger';
            break;
    }
    
    indicator.innerHTML = `<i class="${icon} me-1"></i>${text}`;
}

// 显示加载状态
function showLoading() {
    document.getElementById('loading-overlay').style.display = 'flex';
}

// 隐藏加载状态
function hideLoading() {
    document.getElementById('loading-overlay').style.display = 'none';
}

// 显示通知
function showToast(message, type = 'info') {
    const toast = document.getElementById('toast');
    const toastMessage = document.getElementById('toast-message');
    
    // 设置消息
    toastMessage.textContent = message;
    
    // 设置类型样式
    toast.className = `toast show bg-${type === 'error' ? 'danger' : type === 'success' ? 'success' : 'info'} text-white`;
    
    // 显示toast
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
}

// 便捷通知函数
function showSuccess(message) {
    showToast(message, 'success');
}

function showError(message) {
    showToast(message, 'error');
}

function showInfo(message) {
    showToast(message, 'info');
}

// 加载结果（用于页面刷新后恢复状态）
async function loadResults() {
    try {
        const response = await fetch('/api/results');
        const data = await response.json();
        
        if (data.success) {
            showProcessingResults(data.results);
        }
    } catch (error) {
        console.error('加载结果失败:', error);
    }
}

// 显示处理中状态（用于页面刷新后恢复状态）
function showProcessingInProgress() {
    showProcessingProgress(0);
    updateStatusIndicator('processing', '处理中');
    document.getElementById('start-processing-btn').disabled = true;
}